import React from 'react';
import { Card, Space, Button, Form, Input, Select, DatePicker, Table, Tag, message } from 'antd';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

// 服务类型字典
const serviceTypeDict = [
  { value: 'recharge', label: '充值' },
  { value: 'withdraw', label: '提现' },
  { value: 'consume', label: '消费' },
  { value: 'refund', label: '退款' },
  { value: 'settlement', label: '结算' },
];

// 模拟流水记录
const mockLogs = Array.from({ length: 66 }).map((_, i) => {
  const type = serviceTypeDict[i % serviceTypeDict.length].value;
  const price = ((i + 1) * (i % 3 === 0 ? 5.8 : 7.3));
  return {
    id: `LOG-${String(i).padStart(4, '0')}`,
    username: `user_${i}`,
    equipmentNo: `EQ-${String(200 + i).padStart(4, '0')}`,
    price: price,
    info: `详情说明 ${i}`,
    type: type,
    createTime: dayjs().subtract(i, 'day').format('YYYY-MM-DD HH:mm:ss'),
    updateTime: dayjs().subtract(i - 2, 'day').format('YYYY-MM-DD HH:mm:ss'),
  };
});

export default function WalletRecord() {
  const [form] = Form.useForm();
  const [data] = React.useState(mockLogs);
  const [filtered, setFiltered] = React.useState(mockLogs);

  const columns = [
    { title: '用户账号', dataIndex: 'username', width: 200 },
    { title: '设备号', dataIndex: 'equipmentNo', width: 200 },
    { title: '金额(¥)', dataIndex: 'price', width: 150, render: (v)=> <span style={{ fontWeight: 600 }}>$ {Number(v).toFixed(2)}</span> },
    { title: '详情', dataIndex: 'info' },
    { title: '类型', dataIndex: 'type', width: 160, render: (t)=> <Tag>{serviceTypeDict.find(d=> d.value===t)?.label || t}</Tag> },
    { title: '创建时间', dataIndex: 'createTime', width: 160 },
    { title: '更新时间', dataIndex: 'updateTime', width: 160 },
  ];

  const onSearch = () => {
    const values = form.getFieldsValue();
    const range = values.dateTime;
    const start = range && range.length === 2 ? range[0] : null;
    const end = range && range.length === 2 ? range[1] : null;
    const next = data.filter(row => {
      const matchEq = values.equipmentNo ? row.equipmentNo.includes(values.equipmentNo) : true;
      const matchType = values.serviceType ? row.type === values.serviceType : true;
      const t = dayjs(row.createTime);
      const matchDate = start && end ? (t.isAfter(start) && t.isBefore(end)) : true;
      return matchEq && matchType && matchDate;
    });
    setFiltered(next);
  };

  const onReset = () => {
    form.resetFields();
    setFiltered(data);
  };

  const exportCSV = () => {
    const headers = ['用户账号','设备号','金额(¥)','详情','类型','创建时间','更新时间'];
    const lines = filtered.map(r => [
      r.username,
      r.equipmentNo,
      Number(r.price).toFixed(2),
      r.info,
      serviceTypeDict.find(d=> d.value===r.type)?.label || r.type,
      r.createTime,
      r.updateTime
    ].join(','));
    const csv = [headers.join(','), ...lines].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `wallet_record_${dayjs().format('YYYYMMDD_HHmmss')}.csv`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('已导出（示例CSV）');
  };

  return (
    <div>
      {/* 搜索与导出 */}
      <Card variant="borderless" styles={{ body: { paddingTop: 8, paddingBottom: 8 } }}>
        <Space>
          <Button onClick={exportCSV}>导出</Button>
          <Form form={form} layout="inline">
            <Form.Item name="dateTime">
              <RangePicker showTime />
            </Form.Item>
            <Form.Item name="equipmentNo">
              <Input placeholder="设备号" allowClear style={{ width: 200 }} />
            </Form.Item>
            <Form.Item name="serviceType">
              <Select allowClear placeholder="流水类型" style={{ width: 160 }} options={serviceTypeDict} />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" onClick={onSearch}>查询</Button>
                <Button onClick={onReset}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
        </Space>
      </Card>

      {/* 表格 */}
      <Card title="流水记录" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r)=> r.id}
          dataSource={filtered}
          columns={columns}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 980 }}
        />
      </Card>
    </div>
  );
}